package edu.software.cakehomework.service.impl;

import edu.software.cakehomework.dao.CakeRepository;
import edu.software.cakehomework.dao.TypeRepository;
import edu.software.cakehomework.entity.Cake;
import edu.software.cakehomework.entity.Type;
import edu.software.cakehomework.service.CakeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class CakeServiceImpl implements CakeService {

    @Autowired
    private CakeRepository cakeRepository;

    @Autowired
    private TypeRepository typeRepository;

    @Override
    public Page<Cake> getCakesByType(Type type, Pageable pageable) {
        return cakeRepository.findByType(type, pageable);
    }

    @Override
    public Page<Cake> searchCakes(String keyword, Pageable pageable) {
        // 由于Repository中没有分页的搜索方法，我们需要先获取所有结果，然后手动分页
        List<Cake> cakes = cakeRepository.findByNameContaining(keyword);
        return new PageImpl<>(cakes, pageable, cakes.size());
    }

    @Override
    public List<Cake> getPopularCakesByType(Type type) {
        return cakeRepository.findByTypeOrderBySalesCountDesc(type);
    }

    @Override
    public List<Cake> getCakesWithDiscount() {
        // 由于Repository中没有直接获取所有打折蛋糕的方法，我们需要先获取所有类型，然后合并结果
        List<Type> types = typeRepository.findAll();
        List<Cake> discountedCakes = new ArrayList<>();
        for (Type type : types) {
            discountedCakes.addAll(cakeRepository.findByTypeAndDiscountPriceIsNotNull(type));
        }
        return discountedCakes;
    }

    @Override
    public Cake getCakeById(Integer id) {
        return cakeRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Cake not found"));
    }
}